#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys
import httpUtil
import cmdUtil
from script import datatool
import time
from queue import Queue

import dataUtil    #判断ocr和yolo的数据中是否有指定内容

#cv图片获取队列
CVIMGQUEUE = Queue()
#按下时的坐标
TDPoint = 17
#抬起时的坐标
TUPoint = 0

#摄像头和点击器的坐标偏差
CAMOFFSETX = 9.1
CAMOFFSETY = 49.8

#移动延时
DELAYT = 5

def initOFFSET():
    global CAMOFFSETX,CAMOFFSETY
    f = open('script' + os.sep + 'offset.txt','r')
    dstr = f.read().replace('\n','').replace('\t','').replace('\r','').replace(' ','').replace('，',',')
    f.close()
    tmps = dstr.split(',')
    CAMOFFSETX = float(tmps[0])
    CAMOFFSETY = float(tmps[1])

initOFFSET()

def setOFFSET(dx,dy):
    global CAMOFFSETX,CAMOFFSETY
    CAMOFFSETX = CAMOFFSETX+dx
    CAMOFFSETY = CAMOFFSETY+dy
    outstr = '%.1f,%.1f'%(CAMOFFSETX,CAMOFFSETY)
    f = open('script' + os.sep + 'offset.txt','w')
    f.write(outstr)
    f.close()
    return CAMOFFSETX,CAMOFFSETY
    
#pcvobj:opencv对象,负责图像的获取
#ppsobj:设备物理坐标与屏幕坐标相互变换工具
#pdpong:设备物理坐标计算工具,负责摄像头图像和物理坐标计算
#ppqeue:发送动作指令的数据列队

class RunOBJ(object):
    """docstring for Stat"""
    def __init__(self,pcvobj,ppsobj,pdpobj,pimgObj,ppqeue,selftype):
        #自已的队像类型
        self.tName = selftype
        #opencv对象
        self.cvobj = pcvobj
        #物理坐标与屏幕界面坐标转换工具对象
        self.psobj = ppsobj
        #移动坐标原记录工具对象
        self.dpobj = pdpobj
        #摄像头像素转相对物理坐标工具对象
        self.imgObj = pimgObj
        #动作命令列队
        self.squeue = ppqeue
        #图片交互列队
        self.imgQueue = CVIMGQUEUE
        #地图位标字典
        self.mapNameDict,self.mapIDDict = datatool.mapData()
        #界面按钮坐标字典
        self.uiDict = datatool.uiData()

        #从cvobj获取的图片
        self.img = None

    def delay(self,t):
        time.sleep(t)
    def moveBy(self,x,y):
        self.dpobj.moveby((x,y))
        cmdUtil.moveTo(self.squeue,self.dpobj.p[0],self.dpobj.p[1])
    #移动到摄像头图片像素坐标(px,py),
    def moveToImg(self,px,py):
        (x,y) = self.imgObj.cSToP((px,py))
        self.moveBy(x,y)

    def moveToImgOnce(self,px,py):
        (x,y) = self.imgObj.cSToP((px,py))
        self.moveBy(x+CAMOFFSETX,y+CAMOFFSETY)
        cmdUtil.touchOnce(self.squeue,TDPoint)
        self.moveBy(-CAMOFFSETX,-CAMOFFSETY)
        self.delay(1)
    #点击一次屏幕
    def touchOnce(self,p = None):
        if p:
            self.moveTo(p)
            self.delay(3)
        self.moveBy(CAMOFFSETX,CAMOFFSETY)
        cmdUtil.touchOnce(self.squeue,TDPoint)
        self.moveBy(-CAMOFFSETX,-CAMOFFSETY)
        self.delay(1)
    #移动到屏幕坐标,这里的所有参数都是屏幕坐标
    def moveTo(self,p):
        tmp = self.psobj.cSToP(p) #得到物理坐标
        print('screen point(%d,%d) convent t moveToPoint:(%.1f,%.1f)'%(p[0],p[1],tmp[0],tmp[1]))
        dt = self.dpobj.moveTo(tmp)
        cmdUtil.moveTo(self.squeue,self.dpobj.p[0],self.dpobj.p[1])
        time.sleep(dt)
 

    #使用ocr判断是否有指定文字显示
    def ocrCheckTxt(self,txt,ocrObj = None):
        odat = ocrObj
        if not odat:
            odat = self.ocrImg()
        d = dataUtil.ocrCheckTxt(odat,txt)
        return d
    def yoloCheckType(self,yType,yObj = None):
        ydat = yObj
        if not ydat:
            ydat = self.yoloImg()
        d = dataUtil.yoloCheckObj(ydat,yType)
        return d
        

    #打开世界地图
    def openWorldMap(self):
        p = self.uiDict['worldmap']['p']
        self.moveTo(p)
        self.touchOnce()
        self.delay(2)

    def closeUI(self):
        self.touchOnce(self.uiDict['other']['p'])

    #获取一张图片
    def getImgFromCV2(self):
        self.cvobj.copyImg(self)
        time.sleep(0.1) #延时100毫秒,等图片复制完成
        timeoutTmp = 30 #3秒超时
        while self.imgQueue.empty():
            time.sleep(0.1)
            timeoutTmp -= 1
            if timeoutTmp <= 0:
                self.img = None
                return
        self.img = self.imgQueue.get().dat.copy()
        print('get img')
    def delImg(self):
        if self.img.any():
            del self.img
            self.img = None
    #图像识别,从cvobj获取图像,发送给yolo服务器获取识别结果并返回
    def yoloImg(self,usdImg = False):
        if usdImg:
            dat = httpUtil.httpPostImg(self.img,port = 8890)  #yolo测试
            return dat
        else:
            self.getImgFromCV2()
            if self.img.any():
                dat = httpUtil.httpPostImg(self.img,port = 8890)  #yolo测试
                del self.img
                self.img = None
                return dat
            else:
                print('not get imge from cvobj')
    #文字识别,坐cvobj获限图像,发送给ocr服务器获取识别结果并返回
    #{'2': {'x': 261, 'y': 376, 'w': 121, 'h': 65, 't': 'c', 's': 0.9999446868896484, 'imgW': 1024, 'imgH': 768}, 
    # '5': {'x': 142, 'y': 642, 'w': 121, 'h': 63, 't': 'd', 's': 0.9999322891235352, 'imgW': 1024, 'imgH': 768}, 
    # '3': {'x': 141, 'y': 509, 'w': 119, 'h': 65, 't': 'd', 's': 0.9999170303344727, 'imgW': 1024, 'imgH': 768}, 
    # '6': {'x': 264, 'y': 643, 'w': 119, 'h': 60, 't': 'c', 's': 0.9999086856842041, 'imgW': 1024, 'imgH': 768}, 
    # '4': {'x': 266, 'y': 511, 'w': 113, 'h': 58, 't': 'c', 's': 0.9998126029968262, 'imgW': 1024, 'imgH': 768}, 
    # '1': {'x': 142, 'y': 376, 'w': 116, 'h': 65, 't': 'd', 's': 0.9971083402633667, 'imgW': 1024, 'imgH': 768}, 
    # '0': {'x': 453, 'y': 334, 'w': 159, 'h': 71, 't': 'sq1', 's': 0.9508532285690308, 'imgW': 1024, 'imgH': 768}}
    def ocrImg(self,usdImg = False,):
        if usdImg:
            dat = httpUtil.httpPostImg(self.img,port = 8889)    #ocr测试
            return dat
        else:
            self.getImgFromCV2()
            if self.img.any():
                dat = httpUtil.httpPostImg(self.img,port = 8889)    #ocr测试
                del self.img
                self.img = None
                return dat
            else:
                print('not get imge from cvobj')

def printData(dat):
    if dat:
        if type(dat) == list:
            for i,v in enumerate(dat[0]):
                print(i,v)
        elif type(dat) == dict:
            for k,v in dat.items():
                print(k,v)
        elif type(dat) == str:
            print(dat)
        else:
            print(dat)
            print(type(dat))
    else:
        print('the data is None...')

def test(cvobj,psobj,dpobj,imgObj,pqeue,tType):
    runobj = RunOBJ(cvobj,psobj,dpobj,imgObj,pqeue)
    if tType == 'yolo':
        dat = runobj.yoloImg()
        printData(dat)
        runobj.delay(1)
    elif tType == 'ocr':
        data = runobj.ocrImg()
        printData(data)
        runobj.delay(1)
def run(cvobj,psobj,dpobj,imgObj,pqeue):
    # runobj = RunOBJ(cvobj,psobj,dpobj,imgObj,pqeue)
    print('run script ...')





